//登录弹窗
const { toLogin, uploadImg } = require("../../../utils/api")
const { btoa } = require("../../../utils/base64")
const app = getApp();

// component/sign-dialog/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    code: '',
    nickname: '',
    avatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
    showInput: false,
    resAvataar: '',
    create_mode: 3
  },


  /**
   * 组件的方法列表
   */
  methods: {
    cancelLogin() {
      this.setData({
        show: false
      })
    },

    //确认登陆
    okLogin() {
      let that = this
      that.setData({
        show: false
      })

      wx.login({
        success(e) {
          that.data.code = e.code //拿到的code存储在data中
          that.setData({
            showInput: true
          })
        },
        fail(e) {
          wx.showToast({
            title: '网络异常',
            duration: 2000
          })
          return
        }
      })

    },

    onClose() {
      this.setData({
        showInput: false
      })
    },

    //选择头像 
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail
      var fileManager = wx.getFileSystemManager().readFileSync(e.detail.avatarUrl, "base64");
      this.setData({
        avatar: avatarUrl
      })
      this.uploadAvatar(fileManager)

    },

    uploadAvatar(e) {
      let params = {
        info: e
      }
      uploadImg(params).then((res) => {
        if (res.errcode == 0) {
          this.setData({
            resAvataar: res.src
          })

        }

      })
    },


    onInput(e) {
      this.setData({
        nickname: e.detail.value
      })
    },

    sureLogin() {
      let that = this

      if (that.data.nickname == '') {
        wx.showToast({
          title: '请输入昵称',
          icon: 'none',
        });
      }
      else {
        let params = {
          code: that.data.code,
          nickname: that.data.nickname,
          avatar: that.data.resAvataar,
          shangjiuid: wx.getStorageSync('shangjiuid'),
          create_mode: wx.getStorageSync('create_mode') ? wx.getStorageSync('create_mode') : that.data.create_mode
        }

        toLogin(params).then((res) => {
          if (res.errcode == 0) {
            let resData = res.data
            that.setData({
              showInput: false
            })
            wx.showToast({
              title: '登录成功',
              icon: 'success',
              success: (result) => {

                wx.setStorageSync('jwt', resData.jwt);
                wx.setStorageSync('userInfo', JSON.stringify(resData.user))

                setTimeout(() => {
                  that.triggerEvent("parentFun");
                }, 1000);

              },
            });
          }
        }
        )
      }


    },

  }
})
